// User.js
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';

import { Table, Modal } from 'antd';
import ActivityListABI from '../contract/ABIs/ActivityList.json'; // 活动列表合约 ABI
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI 
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI

import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress.js'; // 材料列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import UserNavBar from './nav/UserNavBar.js';
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';

const User = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractActivityList, setcontractActivityList] = useState(null);
    const [contractMaterialList, setcontractMaterialList] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractUser, setcontractUser] = useState(null);
    const [isUser, setisUser] = useState(false);
    const [IsList, setIsList] = useState(false);//控制是否显示列表
    const [categoryFilter, setCategoryFilter] = useState('');//用于通过分类查询

    // 新增状态变量来存储用户积分 
    // const [userPoints, setUserPoints] = useState(0);
    const [activityId, setactivityId] = useState('');

    const [materialName, setMaterialName] = useState('');// 材料文件名
    const [description, setDescription] = useState('');//材料描述
    const [layer, setLayer] = useState(0);//层次等级
    const [reward, setReward] = useState(0);//获奖等级
    const [userName, setUserName] = useState('');
    const [gender, setGender] = useState('');
    const [phone, setPhone] = useState('');
    const [userInfo, setUserInfo] = useState({});
    const [materialRecords, setMaterialRecords] = useState([]);//返回的数据数组
    const [selectedRecord, setSelectedRecord] = useState(null);
    const [updatedMaterialId, setUpdatedMaterialId] = useState(false);
    const [updateModalOpen, setUpdateModalOpen] = useState(false);
    const [updatedMaterialName, setUpdatedMaterialName] = useState('');
    const [updatedDescription, setUpdatedDescription] = useState('');
    const [updatedLayer, setUpdatedLayer] = useState('');
    const [updatedReward, setUpdatedReward] = useState('');

    const [hideParagraph, setHideParagraph] = useState(true);

    const columns = [
        {
            title: '活动id',
            dataIndex: ['activityId'],
            key: 'activityId',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text.toString()}
                </span>
            )
        },
        {
            title: '材料文件名',
            dataIndex: ['userMaterial', 'materialName'],
            key: 'materialName',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '材料描述',
            dataIndex: ['userMaterial', 'description'],
            key: 'description',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '层次等级',
            dataIndex: ['userMaterial', 'layer'],
            key: 'layer',
            render: (text) => {
                const newText = text.toString();
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <button className="btn btn-primary btn-lg d-block w-100" type="primary" onClick={() => handleUpdateClick(record)}>
                    更新
                </button>
            ),
        }
    ];

    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建活动列表合约实例
                    const activityListInstance = new web3Instance.eth.Contract(
                        ActivityListABI,
                        ActivityListAddress
                    );
                    setcontractActivityList(activityListInstance);

                    // 创建材料列表合约实例
                    const materialListInstance = new web3Instance.eth.Contract(
                        MaterialListABI,
                        MaterialListAddress
                    );
                    setcontractMaterialList(materialListInstance);

                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    // 创建用户合约实例
                    const userInstance = new web3Instance.eth.Contract(
                        UserABI,
                        address
                    );
                    setcontractUser(userInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取用户合约的 owner 地址
                    const ownerAddress = await userInstance.methods.getUserAddr().call();
                    // 检查当前账户是否是用户本人
                    setisUser(currentAddress === ownerAddress);

                    // 自动获取学生信息列表
                    await SelectMaterials(web3Instance, materialListInstance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);


    // 查询用户所有材料函数
    const SelectMaterials = async (web3Instance, materialListInstance) => {
        if (materialListInstance) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3Instance.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);
                const result = await materialListInstance.methods.selectMaterials(fromAddress).call({ from: accounts[0] })
                console.log("所有材料", result);
                setMaterialRecords(result);
                setIsList(true);//让列表显示出来
            } catch (error) {
                console.log(error)
                alert('查询失败');
            }
        }
    };

    const handleUpdateClick = (record) => {
        if (!record || !record.userMaterial) {
            console.error("Record or userMaterial is undefined:", record);
            return;
        }
        setSelectedRecord(record);
        setUpdatedMaterialId(record.id.toString());
        setUpdatedMaterialName(record.userMaterial.materialName);
        setUpdatedDescription(record.userMaterial.description);
        setUpdatedLayer(record.userMaterial.layer.toString());
        setUpdatedReward(record.userMaterial.reward.toString());
        setUpdateModalOpen(true);
    };

    const handleUpdate = async () => {
        // Handle update logic here
        setUpdateModalOpen(false);
        if (contractMaterialList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("materialName:", updatedMaterialId, updatedMaterialName, updatedDescription, updatedLayer, updatedReward);
                // var updatedMaterialIdNumber = Number(updatedMaterialId)
                // 查询材料记录以检查是否已经审核  ,通过审核用户就不能在更新了
                const materialRecord = await contractMaterialList.methods.materialRecords(updatedMaterialId).call({ from: fromAddress });
                if (materialRecord.isReviewed == true) {
                    alert('该材料已经被审核！');
                    return; // 退出函数，不执行后续审核逻辑  
                }
                await contractMaterialList.methods.updateMaterial(updatedMaterialId, updatedMaterialName, updatedDescription, updatedLayer, updatedReward).send({ from: accounts[0] });
                alert('更新成功！');
            } catch (error) {
                console.log(error)
                alert('文件上传失败！，更新失败');
            }
        }
    };
    const handleFilterActivity = async () => {
        if (contractMaterialList) {
            try {
                const filteredActivityList = materialRecords.filter((activity) => activity.materialName === categoryFilter);//设置通过类别查询
                setMaterialRecords(filteredActivityList);

                setIsList(true);
            } catch (error) {
                console.error(error);
            }
        }
    };
    return (
        <div>
            {/* 如果当前账户不是用户，则显示提示信息 */}
            {!isUser && (<div>您没有权限访问此页面。</div>)}

            {/* 用户界面 */}
            {isUser && (
                <div className="page-wrapper" style={{
                    backgroundColor: '#FFFFFF'
                }}>
                    <div className="main-container">
                        <UserNavBar address={address} />

                        <div className="app-container">
                            <Head></Head>
                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">

                                                <div className="container">
                                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                        data-bs-theme="light"
                                                        style={{
                                                            backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                                        }}
                                                    >
                                                        <div className="mb-3">
                                                            <h2>查询当前用户的所有材料</h2>

                                                            <div className="d-flex justify-content-end mt-3">
                                                                <div className="choices">
                                                                    <button className="btn btn-primary btn-lg d-block w-100" > <Link to={`/user/${address}/User_uploadMaterial`} className="choice">上传</Link></button>
                                                                </div>
                                                                <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                                                    <input
                                                                        type="text"
                                                                        className="form-control"
                                                                        placeholder="输入材料名称查询"
                                                                        aria-label="材料名称查询"
                                                                        aria-describedby="basic-addon2"
                                                                        value={categoryFilter}
                                                                        onChange={(e) => setCategoryFilter(e.target.value)}
                                                                    />
                                                                    <div className="input-group-append">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={handleFilterActivity}>搜索</button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            {IsList ? (
                                                                <Table
                                                                    dataSource={materialRecords}
                                                                    columns={columns} // 确保你已经定义了columns
                                                                    pagination={{
                                                                        pageSize: 2,
                                                                        showTotal: false, // 隐藏总页数
                                                                        showSizeChanger: false, // 隐藏页面大小选择器
                                                                        itemRender: (current, type, originalElement) => (
                                                                            <span style={{ color: 'black' }}>
                                                                                {current}
                                                                            </span>
                                                                        ),
                                                                    }}                                                //  onRow={onRow} // 确保你传递了onRow函数，用于保存对应的id
                                                                />
                                                            ) : (
                                                                <div>No activity information available.</div>
                                                            )}


                                                            {/* <div className="mb-3 mt-4">
                                                <button className="btn btn-primary btn-lg d-block w-100" onClick={SelectMaterials}>查询</button>
                                            </div> */}


                                                            {updateModalOpen && (
                                                                <div className="mb-3">
                                                                    <br />
                                                                    <h2>更新选中材料信息</h2><br />
                                                                    <input className="form-control item" id="name" type="text" value={updatedMaterialName} onChange={(e) => setUpdatedMaterialName(e.target.value)} /><br />
                                                                    <input className="form-control item" id="name" type="text" value={updatedDescription} onChange={(e) => setUpdatedDescription(e.target.value)} /><br />
                                                                    <input className="form-control item" id="name" type="text" value={updatedLayer} onChange={(e) => setUpdatedLayer(e.target.value)} /><br />
                                                                    <input className="form-control item" id="name" type="text" value={updatedReward} onChange={(e) => setUpdatedReward(e.target.value)} /><br />
                                                                    <div className="mb-3 mt-4">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" onClick={handleUpdate}>确认更新</button>
                                                                    </div>
                                                                </div>
                                                            )}
                                                        </div>

                                                    </div>
                                                </div>

                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div>
    );
}

export default User;
